package net.danielseidl.ludumdare.ld48.view;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Logger;

import net.danielseidl.ludumdare.ld48.Game;
import net.danielseidl.ludumdare.ld48.character.MoveDirection;

/**
 * Used to react on user key input.
 * 
 * @author    Daniel Seidl - info@daniel-seidl.net
 */
public class UserKeyListener extends KeyAdapter
	{
	private Logger LOGGER = Logger.getLogger(UserKeyListener.class.getName());
	
	private Game game;
	
	/**
	 * Creates a new user key listener.
	 * @param game The game instance to use.
	 */
	public UserKeyListener(Game game)
		{
		this.game = game;
		this.LOGGER.info("user key listener has been created");
		}
	
	/**
	 * Invoked when a key has been pressed by the player.
	 * @param The key that has been pressed.
	 */
	public void keyPressed(KeyEvent key)
		{
		boolean tileUpdate = false;
		
		int code = key.getKeyCode();
		
		if (!this.game.getGameHasStopped())
			{
			switch (code)
				{
				case 37: // move left
					tileUpdate = this.game.getPlayer().movePlayer(MoveDirection.LEFT);
					this.game.getGameView().forceLocationUpdate();
					break;
				case 38: // move up
					tileUpdate = this.game.getPlayer().movePlayer(MoveDirection.UP);
					this.game.getGameView().forceLocationUpdate();
					break;
				case 39: // move right
					tileUpdate = this.game.getPlayer().movePlayer(MoveDirection.RIGHT);
					this.game.getGameView().forceLocationUpdate();
					break;
				case 40: // move down
					tileUpdate = this.game.getPlayer().movePlayer(MoveDirection.DOWN);
					this.game.getGameView().forceLocationUpdate();
					break;
				}
			
			if (tileUpdate)
				{
				this.game.getGameView().forceTileMapUpdate();
				}
			}
		}
	
	/**
	 * Invoked when a key has been typed by the player.
	 * @param The key that has been typed.
	 */
	public void keyTyped(KeyEvent key)
		{
		this.keyPressed(key);
		}

	/**
	 * Invoked when a key has been released by the player.
	 * @param The key that has been released.
	 */
	public void keyReleased(KeyEvent key)
		{
		int code = key.getKeyCode();
		switch (code)
			{
			case 37:
			case 38:
			case 39:
			case 40:
				this.game.getPlayer().stopCharacterImage();
				break;
			}
		}
	}
